﻿using System;
using System.ServiceModel;
using PSE.Framework.ErrorLogging;
using PSE.Updater.Common.Gateway.ServiceContract;
using PSE.Updater.Server.Engine;
using PSE.Updater.Common.Providers;
using Engine = PSE.Updater.Server.Engine;

namespace PSE.Updater.Server.Service
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class UpdatesRegistryProductFoldersService : IUpdatesRegistryProductFolders
    {
        public void AddFolder(ProviderType providerType, string productName, string folder)
        {
            try
            {
                RegistryProduct.Instance.AddProduct(productName);
                RegistryProduct.Instance.AddFolder(providerType, productName, folder);
                RegistryProduct.Instance.Save();

                //Engine.UpdateService.Instance.RegisterFolder(providerType, productName, folder);
            }
            catch (Exception ex)
            {
                ThrowFaultException(ex);
            }
        }

        public void RemoveFolder(ProviderType providerType, string productName, string folder)
        {
            try
            {
                RegistryProduct.Instance.RemoveFolder(providerType, productName, folder);
                RegistryProduct.Instance.Save();
            }
            catch (Exception ex)
            {
                ThrowFaultException(ex);
            } 
        }

        public void RemoveAllFolders(ProviderType providerType, string productName)
        {
            try
            {
                RegistryProduct.Instance.RemoveAllFolders(providerType, productName);
                RegistryProduct.Instance.Save();

                //Engine.UpdateService.Instance.UnregisterProduct(productName);
            }
            catch (Exception ex)
            {
                ThrowFaultException(ex);
            } 
        }

        private void ThrowFaultException(Exception ex)
        {
            ErrorLogger.WriteLog(LogType.Error, ex);
            throw new FaultException(new FaultReason(ex.ToString()), new FaultCode(ex.Message));
        }
    }
}
